import React, { useEffect, useState, useRef, useMemo } from 'react';
import { View, Text, TouchableOpacity, Animated, Easing, Image, ScrollView, Modal, ActivityIndicator, useWindowDimensions, StyleSheet } from 'react-native';
import { AppStyles, AppColors, TextStyles } from '../theme/uiLib.config';
import { useRouter } from 'expo-router';
import Icon from 'react-native-vector-icons/Ionicons';
import { useAIStore } from '../store/ai';
import { Colors } from 'react-native-ui-lib';
import mockMerchants from '../data/mockMerchants';

const images = [
  require('../../assets/images/load_1.png'),
  require('../../assets/images/load_2.png'),
  require('../../assets/images/load_3.png'),
  require('../../assets/images/load_4.png'),
  require('../../assets/images/load_5.png'),
];

interface Merchant {
  id: string;
  name: string;
  points: number;
  image: any;
  category: '通讯账户' | '商超账户' | '本地生活';
}

const merchants: Merchant[] = mockMerchants.filter(merchant => 
  merchant.category === '通讯账户' || 
  merchant.category === '商超账户' || 
  merchant.category === '本地生活'
).map(merchant => ({
  id: merchant.id,
  name: merchant.name,
  points: merchant.points,
  image: merchant.image,
  category: merchant.category as '通讯账户' | '商超账户' | '本地生活',
}));

const MerchantList = () => {
  const router = useRouter();
  const { playAudio, stopAudio } = useAIStore();
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState(merchants.map(() => true));
  const [modalVisible, setModalVisible] = useState(false);
  const loadingTextFade = useRef(new Animated.Value(1)).current;
  const buttonFade = useRef(new Animated.Value(0)).current;
  const imageAnimations = useRef(images.map(() => new Animated.Value(0))).current;
  const { width } = useWindowDimensions();
  const buttonWidth = width * 0.9;
  const buttonHeight = 100;
  const horizontalPadding = 20;

  const styles = useMemo(() => StyleSheet.create({
    merchantItemContainer: {
      opacity: buttonFade,
      marginBottom: 10,
      paddingHorizontal: horizontalPadding,
    },
    merchantItemButton: {
      borderRadius: 6,
      flexDirection: 'row',
      alignItems: 'center',
      width: '100%',
      height: buttonHeight,
      backgroundColor: '#fff',
    },
    merchantLogo: {
      width: 80,
      height: 80,
      marginLeft: 10,
      marginRight: 15,
      opacity: 0.9,
      borderColor: Colors.grey20,
      borderWidth: 0.5,
      aspectRatio: 1,
      borderRadius: 6,
    },
    merchantName: {
      textAlign: 'left',
      fontWeight: 'bold',
      marginTop: 0,
    },
    merchantPoints: {
      textAlign: 'left',
      marginTop: 5,
      color: Colors.golden,
    },
    selectedIndicator: {
      backgroundColor: AppColors.success,
      borderRadius: 12,
      width: 24,
      height: 24,
      justifyContent: 'center',
      alignItems: 'center',
      right: 10,
    },
  }), [buttonFade, buttonWidth, buttonHeight, horizontalPadding]);


  useEffect(() => {
    playAudio(require('../../assets/audio/wait_plz.mp3'));

    const imageAnimationSequence = images.map((_, index) => {
      return Animated.sequence([
        Animated.timing(imageAnimations[index], {
          toValue: 1,
          duration: 100,
          useNativeDriver: false
        }),
        Animated.delay(500),
        Animated.timing(imageAnimations[index], {
          toValue: 0,
          duration: 100,
          useNativeDriver: false
        })
      ]);
    });

    const animationSequence = Animated.parallel([
      Animated.sequence(imageAnimationSequence),
      Animated.timing(buttonFade, {
        toValue: 1,
        duration: 500,
        delay: 3000,
        easing: Easing.linear,
        useNativeDriver: false
      })
    ]);

    animationSequence.start(() => {
      setLoading(false);
      stopAudio();
      playAudio(require('../../assets/audio/union_list.mp3'));
    });

    return () => {
      animationSequence.stop();
      stopAudio();
    };
  }, [playAudio, stopAudio, buttonFade, imageAnimations]);

  const toggleSelect = (index: number) => {
    const newSelected = [...selected];
    newSelected[index] = !newSelected[index];
    setSelected(newSelected);
  };

  const handleBind = () => {
    stopAudio();
    setModalVisible(true);
    setTimeout(() => {
      setModalVisible(false);
      router.push('/BindSuccess');
    }, 1000);
  };

  const getCategoryCount = (category: '通讯账户' | '商超账户' | '本地生活') => {
    return merchants.filter((merchant, index) => merchant.category === category && selected[index]).length;
  };

  return (
    <View style={{ flex: 1, paddingVertical: 20 }}>
      <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 34, paddingHorizontal: horizontalPadding }}>
        <TouchableOpacity onPress={() => router.push('/')} style={{ marginRight: 10 }}>
          <Icon name="chevron-back-outline" size={24} color={AppColors.secondary} />
        </TouchableOpacity>
      </View>

      <View style={{ alignItems: 'center', marginTop: 30 }}>
        <Text style={{ fontSize: 24, textAlign: 'center', fontWeight: 'bold' }}>选择积分账户</Text>
        <Text style={[TextStyles.grey20, { fontSize: 16, textAlign: 'center', marginTop: 10, color: Colors.grey20 }]}>
          查询到以下积分账户，请选择
        </Text>
      </View>

      {loading && (
        <View style={{
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          justifyContent: 'center',
          alignItems: 'center',
          zIndex: 2
        }}>
          <View style={{
            height: 80,
            justifyContent: 'center',
            alignItems: 'center',
          }}>
            {images.map((image, index) => (
              <Animated.Image
                key={index}
                source={image}
                style={{
                  opacity: imageAnimations[index],
                  width: 50,
                  height: 50,
                  position: 'absolute'
                }}
              />
            ))}
          </View>

          <Animated.Text
            style={{
              opacity: loadingTextFade,
              fontSize: 18,
              textAlign: 'center',
            }}
          >
            正在查询可绑定账户
          </Animated.Text>
        </View>
      )}

      <ScrollView
        showsVerticalScrollIndicator={false}
        showsHorizontalScrollIndicator={false}
      >
        {!loading && (
          <View style={{ flex: 1, marginTop: 30 }}>
            {/* 账户列表 */}
            {['通讯账户', '商超账户', '本地生活'].map((category) => (
              <View key={category} style={{ marginTop: 25 }}>
                <View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 20, paddingHorizontal: horizontalPadding }}>
                  <Icon name={
                    category === '通讯账户' ? 'phone-portrait-outline' :
                      category === '商超账户' ? 'bag-add-outline' : 'location-outline'
                  } size={20} color={AppColors.primary} />
                  <Text style={[{ marginLeft: 10, fontSize: 20 }]}>{category}</Text>
                  <Text style={TextStyles.primary}>
                    （{getCategoryCount(category as '通讯账户' | '商超账户' | '本地生活')}）
                  </Text>
                </View>
                {merchants
                  .filter(merchant => merchant.category === category)
                  .map((merchant, index) => (
                    <Animated.View
                      key={merchant.id}
                      style={styles.merchantItemContainer}
                    >
                      <TouchableOpacity
                        style={styles.merchantItemButton}
                        onPress={() => toggleSelect(index)}
                      >
                        <Image
                          source={merchant.image}
                          style={styles.merchantLogo}
                          resizeMode="contain"
                        />
                        <View style={{ flex: 1, justifyContent: 'flex-start' }}>
                          <Text style={[TextStyles.primaryBold, styles.merchantName]}>{merchant.name}</Text>
                          <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                            <Icon name="server" size={16} color={Colors.golden} />
                            <Text style={[TextStyles.number, styles.merchantPoints]}>{merchant.points} </Text>
                          </View>
                        </View>
                        {selected[index] && (
                          <View style={styles.selectedIndicator}>
                            <Icon
                              name="checkmark"
                              size={18}
                              color="#fff"
                            />
                          </View>
                        )}
                      </TouchableOpacity>
                    </Animated.View>
                  ))}
              </View>
            ))}

            <TouchableOpacity
              style={{
                alignSelf: 'center',
                justifyContent: 'center',
                width: '90%',
                height: 60,
                backgroundColor: AppColors.primary,
                paddingVertical: 15,
                borderRadius: 24,
                marginBottom: 120,
              }}
              onPress={handleBind}
            >
              <Text style={[TextStyles.h3, { color: '#fff', textAlign: 'center' }]}>绑定</Text>
            </TouchableOpacity>
          </View>
        )}
      </ScrollView>

      <Modal
        transparent={true}
        animationType="fade"
        visible={modalVisible}
      >
        <View style={{
          flex: 1,
          justifyContent: 'center',
          alignItems: 'center',
          backgroundColor: 'rgba(0, 0, 0, 0.7)',
        }}>
          <View style={{
            width: "80%",
            padding: 20,
            backgroundColor: 'white',
            borderRadius: 12,
            alignItems: 'center',
          }}>
            <ActivityIndicator size="large" color={AppColors.primary} />
            <Text style={[TextStyles.primary, { marginTop: 10 }]}>绑定中，请稍等</Text>
          </View>
        </View>
      </Modal>
    </View>
  );
};

export default MerchantList;